package com.linkai.onlinetool.controller;

import com.alibaba.fastjson.JSON;
import com.linkai.onlinetool.entity.AIImage;
import com.linkai.onlinetool.service.AIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AIController {

    @Autowired
    private AIService aiService;

    /*

        <form action="http://localhost:8001/aiimage" enctype="multipart/form-data" method="post">
    需要识别的图片：<input type="file" name="file">
    <input type="submit" value="upload">
</form>

    * */

    @RequestMapping("/aiimage")
//    @CrossOrigin(value = "http://101.132.147.111:8080", maxAge = 1800, allowedHeaders = "*")
    @CrossOrigin(allowCredentials="true",maxAge = 3600)
    public String imageToWord(@RequestParam("file") MultipartFile file , HttpServletRequest request, Model model) throws IOException {

        // 1. 文件上传,返回上传之后新的文件名称
        // 返回文件的全路径 url
        String fileUrl = aiService.uploadImage(file, request);
        System.out.println("fileUrl = " + fileUrl);

        // 2. 图片中文字内容识别
        InputStream is = file.getInputStream();
        String resultWord = null;
        try {
            resultWord = aiService.myRecognizeCharacter(is);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, String> map = new HashMap<>();
        map.put("imagURL", fileUrl);
        map.put("result", resultWord);

        AIImage aiImage = new AIImage(fileUrl, resultWord);
        String result = JSON.toJSONString(aiImage);
        Object result2 = JSON.toJSON(aiImage);
        System.out.println("s = " + result);
        System.out.println("result2 = " + result2.toString());
        System.out.println("result = " + result);

//        model.addAttribute("result", "/upload/" + newFileName);
//        model.addAttribute("word", resultWord);
        String resultJSON = "{\"text\":\"" + resultWord + "\"," + "\"url\":\"" + fileUrl + "\"}";
        System.out.println("resultJSON" + resultJSON);
        // 这里暂时只返回识别出的结果，不返回图片的url
        System.out.println("最终返回的结果 resultWord =" + resultWord);
        return resultWord;

        // *************



    }



}
